from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, Index

# 数据库配置
db_config = {
    "sqlite": {"engine": "sqlite:///mydatabase.db"},
    "mysql": {"engine": "mysql+pymysql://haojg:root@127.0.0.1/stock"},
}

# 根据配置选择 engine
db_choice = "sqlite"
if db_choice == "sqlite":
    engine = create_engine(db_config["sqlite"]["engine"])
elif db_choice == "mysql":
    engine = create_engine(db_config["mysql"]["engine"])
else:
    engine = create_engine("sqlite:///mydatabase.db")

Session = sessionmaker(bind=engine)

Base = declarative_base()


class Address(Base):
    __tablename__ = "address"
    id = Column(Integer, primary_key=True, autoincrement=True)
    address = Column(String)


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, autoincrement=True)
    addr_id = Column(Integer, ForeignKey("address.id"))
    name = Column(String)
    age = Column(Integer)

    def __repr__(self):
        return f"<User(id='{self.id}', name='{self.name}', age='{self.age}')>"


class Author(Base):
    __tablename__ = "author"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    books = relationship("Book", back_populates="author")


class Book(Base):
    __tablename__ = "book"
    id = Column(Integer, primary_key=True)
    title = Column(String)
    author_id = Column(Integer, ForeignKey("author.id"))
    author = relationship("Author", back_populates="books")


class Department(Base):
    __tablename__ = "department"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    employees = relationship("Employee", back_populates="department")


class Employee(Base):
    __tablename__ = "employee"
    id = Column(Integer, primary_key=True)
    name = Column(String)
    remark = Column(String)
    score = Column(Integer)
    department_id = Column(Integer, ForeignKey("department.id"))
    department = relationship("Department", back_populates="employees")


class Code(Base):
    __tablename__ = "code"
    id = Column(Integer, primary_key=True)
    symbol = Column(String)
    exchange = Column(String)
    remark = Column(String)
    # 复合唯一索引
    __table_args__ = (Index("ix_vt_symbol", "symbol", "exchange", unique=True),)


Base.metadata.create_all(engine)
